#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_pwm.h"
#include "iot_errno.h"
#include "hi_io.h"

#define RED_LED_PIN_NAME 2
#define GREEN_LED_PIN_NAME 7
#define BLUE_LED_PIN_NAME 8

#define RED_LED_PIN_FUNCTION HI_IO_FUNC_GPIO_2_PWM2_OUT
#define GREEN_LED_PIN_FUNCTION HI_IO_FUNC_GPIO_7_PWM0_OUT
#define BLUE_LED_PIN_FUNCTION HI_IO_FUNC_GPIO_8_PWM1_OUT

#define IOT_PWM_DUTY_MAX  100
#define PWM_FREQ_DIVITION 64000
#define DELAY_US 250000
#define STACK_SIZE (4096)
#define PWM_PORT_NUM  (2)
#define DOUBLE  (2)
#define TIMES  (3)  // 亮 3 次

static void PWMLedDemoTask(void)
{
    // 设置GPIO复用功能（保持原代码不变）
    hi_io_set_func(RED_LED_PIN_NAME, RED_LED_PIN_FUNCTION);
    hi_io_set_func(GREEN_LED_PIN_NAME, GREEN_LED_PIN_FUNCTION);
    hi_io_set_func(BLUE_LED_PIN_NAME, BLUE_LED_PIN_FUNCTION);

    // 初始化所有PWM通道（按通道号初始化）
    IoTPwmInit(2);  // 通道2（对应红色）
    IoTPwmInit(0);  // 通道0（对应绿色）
    IoTPwmInit(1);  // 通道1（对应蓝色）

    for (int time = 0; time < TIMES; time++) {
        // 红灯控制 - 使用通道2
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(2, i, PWM_FREQ_DIVITION);  // 通道2
            usleep(DELAY_US);
            IoTPwmStop(2);
        }

        // 绿灯控制 - 使用通道0
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(0, i, PWM_FREQ_DIVITION);  // 通道0
            usleep(DELAY_US);
            IoTPwmStop(0);
        }

        // 蓝灯控制 - 使用通道1
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(1, i, PWM_FREQ_DIVITION);  // 通道1
            usleep(DELAY_US);
            IoTPwmStop(1);
        }
    }

    // 停止所有PWM
    IoTPwmStop(2);
    IoTPwmStop(0);
    IoTPwmStop(1);
}

static void PWMLedDemo(void)
{
    osThreadAttr_t attr;

    // 初始化 RGB LED 的引脚
    IoTGpioInit(RED_LED_PIN_NAME);
    IoTGpioInit(GREEN_LED_PIN_NAME);
    IoTGpioInit(BLUE_LED_PIN_NAME);

    attr.name = "PWMLedDemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = STACK_SIZE;
    attr.priority = osPriorityNormal;

    if (osThreadNew(PWMLedDemoTask, NULL, &attr) == NULL) {
        printf("[ColorfulLightDemo] Failed to create PWMLedDemoTask!\n");
    }
}
APP_FEATURE_INIT(PWMLedDemo);